package com.janwen.spring.ws.client;

import java.io.StringReader;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.transport.http.CommonsHttpMessageSender;

/**
 * @author janwen Mar 7, 2013 5:06:53 PM
 * 
 */
public class WebServiceClient {

	//private static final String MESSAGE = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><getSupportCity xmlns=\"http://WebXml.com.cn/\"><byProvinceName>北京</byProvinceName></getSupportCity></soap:Body></soap:Envelope>";

	private static final String MESSAGE =  "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><GetWeather xmlns=\"http://www.webserviceX.NET\"><CityName>beijing</CityName><CountryName>China</CountryName></GetWeather></soap:Body></soap:Envelope>";
	
	
	private final WebServiceTemplate webServiceTemplate = new WebServiceTemplate();

	public void setDefaultUri(String defaultUri) {
		webServiceTemplate.setDefaultUri(defaultUri);
	}

	public static void main(String[] args) {
		new WebServiceClient().customSendAndReceive();
	}
	// send to the configured default URI
	public void simpleSendAndReceive() {
		StreamSource source = new StreamSource(new StringReader(MESSAGE));
		StreamResult result = new StreamResult(System.out);
		webServiceTemplate.sendSourceAndReceiveToResult(source, result);
	}

	static final String wetherurl = "http://www.webservicex.net/globalweather.asmx/";
	// send to an explicit URI
	public  void customSendAndReceive() {
		System.out.println(MESSAGE);
		HttpClient httpClient = new DefaultHttpClient();
		CommonsHttpMessageSender httpMessageSender = new CommonsHttpMessageSender();
		/*
		 * 提示:The type org.apache.commons.httpclient.HttpClient cannot be resolved. It is indirectly referenced from required .class files
		 *源代码中提示:
		 *- sun.net.www.http.HttpClient
	        -org.apache.http.client.HttpClient
	        这个级联关系啥意思啊?
		 *
		 */
		//httpMessageSender.setHttpClient(httpClient);
		webServiceTemplate.setMessageSender(httpMessageSender);
		StreamSource source = new StreamSource(new StringReader(MESSAGE));
		StreamResult result = new StreamResult(System.out);
		webServiceTemplate.sendSourceAndReceiveToResult(
				wetherurl, source, result);
	}
}
